package nl.hva.three2learn.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import nl.hva.three2learn.model.User;

@Repository
public final class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public User findByEmail(String email) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		//Case insensitive search.
		Query q = session.createQuery("from User u where lower(u.email) = :email");
		q.setString("email", email.toLowerCase());

		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (User) result;
	}
	
	@Override
	public List<User> findAllUsers() {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from User");
		
		List<User> users = q.list();
		
		session.getTransaction().commit();
		
		return users;
	}

	@Override
	public List<User> findAllActiveUsers() {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from User u where u.isActive = true");
		
		List<User> users = q.list();
		
		session.getTransaction().commit();
		
		return users;
	}
	
	@Override
	public User findById(long userId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from User u where u.id = :id");
		q.setLong("id", userId);
		
		User user = (User) q.uniqueResult();
		
		session.getTransaction().commit();
		
		return user;
	}

	@Override
	public void save(User user) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(user);
		session.getTransaction().commit();
	}

	@Override
	public void enable(User user) {
		
		// User isn't disabled - do nothing
		if (!user.isDisabled())
			return;
			
		user.setDisabled(false);
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(user);
		session.getTransaction().commit();
	}
	
	@Override
	public void disable(User user) {
		
		// User is already disabled - returnnnn
		if (user.isDisabled())
			return;
		
		user.setDisabled(true);
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(user);
		session.getTransaction().commit();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public boolean emailUnique(String email) {
		return findByEmail(email) == null;
	}
}